package com.codeest.geeknews.ui.main.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.design.internal.NavigationMenuPresenter;
import android.support.design.internal.NavigationMenuView;
import android.support.design.widget.NavigationView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.codeest.geeknews.R;
import com.codeest.geeknews.app.Constants;
import com.codeest.geeknews.base.BaseActivity;
import com.codeest.geeknews.base.contract.main.DoubanContract;
import com.codeest.geeknews.media.music.IMediaPlaybackService;
import com.codeest.geeknews.media.music.MediaPlaybackService;
import com.codeest.geeknews.media.music.MusicUtils;
import com.codeest.geeknews.model.bean.DoubanLoginBean;
import com.codeest.geeknews.presenter.main.DoubanPresenter;
import com.codeest.geeknews.ui.gank.fragment.GankMainFragment;
import com.codeest.geeknews.ui.gold.fragment.GoldMainFragment;
import com.codeest.geeknews.ui.main.fragment.AboutFragment;
import com.codeest.geeknews.ui.main.fragment.LikeFragment;
import com.codeest.geeknews.ui.main.fragment.SettingFragment;
import com.codeest.geeknews.ui.vtex.fragment.VtexMainFragment;
import com.codeest.geeknews.ui.wechat.fragment.WechatMainFragment;
import com.codeest.geeknews.ui.zhihu.fragment.ZhihuMainFragment;
import com.codeest.geeknews.util.StatusBarUtil;
import com.codeest.geeknews.widget.PlayingAnimationBar;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by Dmytro Denysenko on 5/4/15.
 */
public class MainActivity3 extends BaseActivity<DoubanPresenter> implements/*LasfmMusicFragment.MusicInteraction,*/
        DoubanContract.LoginView, ServiceConnection {
    private static final long RIPPLE_DURATION = 250;


    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.root)
    FrameLayout root;
    @BindView(R.id.shake_view)
    PlayingAnimationBar shake_view;
    //@BindView(R.id.navigation)
    NavigationView mNavigationView;
    //
    ZhihuMainFragment mZhihuFragment;
    GankMainFragment mGankFragment;
    WechatMainFragment mWechatFragment;
    GoldMainFragment mGoldFragment;
    VtexMainFragment mVtexFragment;
    LikeFragment mLikeFragment;
    SettingFragment mSettingFragment;
    AboutFragment mAboutFragment;
    //
    private int hideFragment = Constants.TYPE_ZHIHU;
    private int showFragment = Constants.TYPE_ZHIHU;
    private SlidingMenu menu;
    //
    MenuItem mLastMenuItem;
    MenuItem mSearchMenuItem;
    private IMediaPlaybackService mService = null;
    private MusicUtils.ServiceToken mToken;

    @OnClick(R.id.music)
    public void musicPlayer() {
        startMusicActivity();
    }

    /**
     * 由于recreate 需要特殊处理夜间模式
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showHideFragment(getTargetFragment(showFragment), getTargetFragment(hideFragment));
        //--------------------------------------------------------------------------------------
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);
        //menu.setMode(SlidingMenu.LEFT_RIGHT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        menu.setTouchModeBehind(SlidingMenu.TOUCHMODE_FULLSCREEN);
        // 设置触摸屏幕的模式
        //menu.setFadeDegree(0.35f);
        menu.setFitsSystemWindows(true);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setBehindScrollScale(0.5f);//在滑动时形成视差滚动，1f 将没有视差效果
        menu.setFadeEnabled(true);//设置滑动时菜单的是否渐变
        menu.setMenu(R.layout.menu_main);
        //View rightView = LayoutInflater.from(this).inflate(R.layout.menu_right, null);
        //menu.setSecondaryMenu(rightView);
        //状态栏透明和间距处理
        {
            if (Build.VERSION.SDK_INT >= 16) {
                ViewGroup.LayoutParams lp = menu.getLayoutParams();
                if (lp instanceof ViewGroup.MarginLayoutParams) {
                    ((ViewGroup.MarginLayoutParams) lp).topMargin -= StatusBarUtil.getStatusBarHeight(this);//增高
                }
                menu.setLayoutParams(lp);
            }
            StatusBarUtil.setPaddingSmart(this, mToolbar);
        }
        mNavigationView = (NavigationView) menu.findViewById(R.id.navigation);
        View headerView = mNavigationView.getHeaderView(0);
        ImageView drawer_cover = (ImageView) headerView.findViewById(R.id.drawer_cover);
        //
        mLastMenuItem = mNavigationView.getMenu().findItem(R.id.drawer_zhihu);
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.drawer_zhihu:
                        showFragment = Constants.TYPE_ZHIHU;
                        //mSearchMenuItem.setVisible(false);
                        break;
                    case R.id.drawer_gank:
                        showFragment = Constants.TYPE_GANK;
                        //mSearchMenuItem.setVisible(true);
                        break;
                    case R.id.drawer_wechat:
                        showFragment = Constants.TYPE_WECHAT;
                        //mSearchMenuItem.setVisible(true);
                        break;
                    case R.id.drawer_gold:
                        showFragment = Constants.TYPE_GOLD;
                        //mSearchMenuItem.setVisible(false);
                        break;
                    case R.id.drawer_vtex:
                        showFragment = Constants.TYPE_VTEX;
                        //mSearchMenuItem.setVisible(false);
                        break;
                    case R.id.drawer_setting:
                        showFragment = Constants.TYPE_SETTING;
                        //mSearchMenuItem.setVisible(false);
                        break;
                    case R.id.drawer_like:
                        showFragment = Constants.TYPE_LIKE;
                        //mSearchMenuItem.setVisible(false);
                        break;
                    case R.id.drawer_about:
                        showFragment = Constants.TYPE_ABOUT;
                        //mSearchMenuItem.setVisible(false);
                        break;
//                    case R.id.drawer_music:
//                        startMusicActivity();
//                        return true;
                }
                if (mLastMenuItem != null) {
                    mLastMenuItem.setChecked(false);
                }
                mLastMenuItem = menuItem;
                //mPresenter.setCurrentItem(showFragment);
                menuItem.setChecked(true);
                //mToolbar.setTitle(menuItem.getTitle());
                setTitle(menuItem.getTitle());
                showHideFragment(getTargetFragment(showFragment), getTargetFragment(hideFragment));
                hideFragment = showFragment;
                menu.post(new Runnable() {
                    @Override
                    public void run() {
                        menu.toggle(true);
                    }
                });
                return true;
            }
        });
        //去掉 NavigationView 的Menu的分割线
        setNavigationMenuLineStyle(mNavigationView, 0, 0);
        //
        IntentFilter f = new IntentFilter();
        f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
        f.addAction(MediaPlaybackService.META_CHANGED);
        registerReceiver(mStatusListener, f);
        mToken = MusicUtils.bindToService(this, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MusicActivity.isMusicActivityTop) {
            startMusicActivity();
        }
        //shake_view.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //shake_view.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mStatusListener);
        MusicUtils.unbindFromService(mToken);
    }

    //播放状态监听
    private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(MediaPlaybackService.META_CHANGED)) {
                // redraw the artist/title info and
                // set new max for progress bar

            } else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
                try {
                    if (mService != null && mService.isPlaying()) {//播放状态
                        shake_view.start();
                    } else {
                        shake_view.reset();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private void startMusicActivity() {
        startActivity(new Intent(MainActivity3.this, MusicActivity.class));
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
//        overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_top_out);
    }

    /**
     * 去掉 NavigationView 的Menu的分割线
     */
    public static void setNavigationMenuLineStyle(NavigationView navigationView, @ColorInt final int color, final int height) {
        try {
            Field fieldByPressenter = navigationView.getClass().getDeclaredField("mPresenter");
            fieldByPressenter.setAccessible(true);
            NavigationMenuPresenter menuPresenter = (NavigationMenuPresenter) fieldByPressenter.get(navigationView);
            Field fieldByMenuView = menuPresenter.getClass().getDeclaredField("mMenuView");
            fieldByMenuView.setAccessible(true);
            final NavigationMenuView mMenuView = (NavigationMenuView) fieldByMenuView.get(menuPresenter);
            mMenuView.setOverScrollMode(View.OVER_SCROLL_NEVER);
            mMenuView.setVerticalScrollBarEnabled(false);
            mMenuView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {
                @Override
                public void onChildViewAttachedToWindow(View view) {
                    RecyclerView.ViewHolder viewHolder = mMenuView.getChildViewHolder(view);
                    if (viewHolder != null && "SeparatorViewHolder".equals(viewHolder.getClass().getSimpleName()) && viewHolder.itemView != null) {
                        if (viewHolder.itemView instanceof FrameLayout) {
                            FrameLayout frameLayout = (FrameLayout) viewHolder.itemView;
                            View line = frameLayout.getChildAt(0);
                            line.setBackgroundColor(color);
                            line.getLayoutParams().height = height;
                            line.setLayoutParams(line.getLayoutParams());
                        }
                    }
                }

                @Override
                public void onChildViewDetachedFromWindow(View view) {

                }
            });
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }


    @Override
    public void setTitle(CharSequence title) {
        ((TextView) mToolbar.findViewById(R.id.title)).setText(title);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main3;
    }

    @Override
    protected void initEventAndData() {
        setTitle("知乎日报");
        mZhihuFragment = new ZhihuMainFragment();
        mGankFragment = new GankMainFragment();
        mWechatFragment = new WechatMainFragment();
        mGoldFragment = new GoldMainFragment();
        mVtexFragment = new VtexMainFragment();
        mLikeFragment = new LikeFragment();
        mSettingFragment = new SettingFragment();
        mAboutFragment = new AboutFragment();
        loadMultipleRootFragment(R.id.fl_main_content, 0, mZhihuFragment, mWechatFragment, mGankFragment, mGoldFragment, mVtexFragment, mLikeFragment, mSettingFragment, mAboutFragment);
        mToolbar.setNavigationIcon(R.drawable.ic_menu);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menu.toggle(true);
            }
        });
        mPresenter.login("luckyjmcc@163.com", "aman14725");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        item.setVisible(false);
        //mSearchView.setMenuItem(item);
        //mSearchMenuItem = item;
        return true;
    }

    private void setTitle(String title) {
        ((TextView) mToolbar.findViewById(R.id.title)).setText(title);
    }

    public void onInformationClick(View view) {
        handleClick(view);
    }

    public void onSettingClick(View view) {
        handleClick(view);
    }

    public void onOtherClick(View view) {
        handleClick(view);
    }

    private void handleClick(View view) {
        switch (view.getId()) {
            case R.id.drawer_zhihu:
                showFragment = Constants.TYPE_ZHIHU;
                break;
            case R.id.drawer_gank:
                showFragment = Constants.TYPE_GANK;
                break;
            case R.id.drawer_wechat:
                showFragment = Constants.TYPE_WECHAT;
                break;
            case R.id.drawer_gold:
                showFragment = Constants.TYPE_GOLD;
                break;
            case R.id.drawer_vtex:
                showFragment = Constants.TYPE_VTEX;
                break;
            case R.id.drawer_setting:
                showFragment = Constants.TYPE_SETTING;
                break;
            case R.id.drawer_like:
                showFragment = Constants.TYPE_LIKE;
                break;
            case R.id.drawer_about:
                showFragment = Constants.TYPE_ABOUT;
                break;
        }
        setTitle((String) view.getTag());
        showHideFragment(getTargetFragment(showFragment), getTargetFragment(hideFragment));
        hideFragment = showFragment;
    }

    private SupportFragment getTargetFragment(int item) {
        switch (item) {
            case Constants.TYPE_ZHIHU:
                return mZhihuFragment;
            case Constants.TYPE_GANK:
                return mGankFragment;
            case Constants.TYPE_WECHAT:
                return mWechatFragment;
            case Constants.TYPE_GOLD:
                return mGoldFragment;
            case Constants.TYPE_VTEX:
                return mVtexFragment;
            case Constants.TYPE_LIKE:
                return mLikeFragment;
            case Constants.TYPE_SETTING:
                return mSettingFragment;
            case Constants.TYPE_ABOUT:
                return mAboutFragment;
        }
        return mZhihuFragment;
    }

    private int getCurrentItem(int item) {
        switch (item) {
            case Constants.TYPE_ZHIHU:
                return R.id.drawer_zhihu;
            case Constants.TYPE_GANK:
                return R.id.drawer_gank;
            case Constants.TYPE_WECHAT:
                return R.id.drawer_wechat;
            case Constants.TYPE_GOLD:
                return R.id.drawer_gold;
            case Constants.TYPE_VTEX:
                return R.id.drawer_vtex;
            case Constants.TYPE_LIKE:
                return R.id.drawer_like;
            case Constants.TYPE_SETTING:
                return R.id.drawer_setting;
            case Constants.TYPE_ABOUT:
                return R.id.drawer_about;
        }
        return R.id.drawer_zhihu;
    }


    @Override
    public void onBackPressedSupport() {
        if (menu.isMenuShowing()) {
            menu.toggle();
        } else {
            super.onBackPressedSupport();
        }
    }

//    @Override
//    public void toggleMenu() {
//        menu.toggle(true);
//    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void loginSucceed(DoubanLoginBean doubanLoginBean) {

    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mService = IMediaPlaybackService.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}
